package com.doge.calcalbum.business.album

import com.doge.calcalbum.R
import com.doge.calcalbum.db.model.Album
import com.doge.calcalbum.db.model.AlbumCover
import com.doge.calcalbum.db.model.AlbumTitle
import com.doge.calcalbum.utils.*

class AlbumRepository {
    val pictureAlbumList = db.albumDao().query(Album.TYPE_PICTURE)
    val videoAlbumList = db.albumDao().query(Album.TYPE_VIDEO)


    fun updateTitle(album: AlbumTitle) = runInTransaction {
        db.albumDao().updateTitle(album)
    }

    fun updateCover(data: AlbumCover) = runInTransaction {
        db.albumDao().updateCover(data)
    }

    fun delete(album: Album) = runInTransaction { db.albumDao().delete(album) }
    fun insert(album: Album) = runInTransaction { db.albumDao().insert(album) }


    init {
        initializedDefaultPictureAlbum()
        initializedDefaultVideoAlbum()
    }

    private fun initializedDefaultPictureAlbum() = runOnWork {
        db.albumDao().queryById(Album.DEFAULT_PICTURE_ID) ?: (
                Album(
                    id = Album.DEFAULT_PICTURE_ID,
                    null,
                    getString(R.string.default_album),
                    1,
                    0,
                    Album.TYPE_PICTURE
                ).also { db.albumDao().insert(it) })
    }

    private fun initializedDefaultVideoAlbum() = runOnWork {
        db.albumDao().queryById(Album.DEFAULT_VIDEO_ID) ?: (
                Album(
                    id = Album.DEFAULT_VIDEO_ID,
                    null,
                    getString(R.string.default_album_video),
                    1,
                    0,
                    Album.TYPE_VIDEO
                ).also { db.albumDao().insert(it) })
    }


    fun totalCount(albumType: Int): Int {
        return db.entryDao().queryTotalCount(albumType)
    }

    companion object {
        private var INS: AlbumRepository? = null

        fun get(): AlbumRepository {
            return INS ?: synchronized(this) {
                INS ?: AlbumRepository().also { INS = it }
            }
        }
    }
}